package com.chenfan.magic.interpreter.classloader;

import com.chenfan.magic.core.IdcEngineEntry;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;

/**
 * @author lm
 * java 编译解释器自定义类加载器
 * <p>
 * 重写类加载器达到加载指定目录的类
 */
public class JavaInterpreterClassLoader extends ClassLoader {

    @Override
    public Class<?> findClass(String name) {
        return findClass(null, "", name);
    }

    public Class<?> findClass(Map<String, Object> idcRuntimePool, String classPath, String name) {
        String myPath = new File(classPath + name + ".class").toURI().toString();
        byte[] cLassBytes = null;
        Path path = null;
        try {
            path = Paths.get(new URI(myPath));
            cLassBytes = Files.readAllBytes(path);
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
            IdcEngineEntry.throwException(idcRuntimePool, null, e);
        }
        Class clazz = defineClass(name, cLassBytes, 0, cLassBytes.length);
        return clazz;
    }
}
